
import React, { useState, useEffect } from 'react';
import FaqItem from '../components/FaqItem';
import SeoHead from '../components/SeoHead';
import { useLocalization } from '../hooks/useLocalization';
import { generateFaqContent } from '../services/geminiService';
import type { FaqItemType } from '../types';
import { LoadingIcon } from '../components/icons';

const FaqPage: React.FC = () => {
    const { t, language } = useLocalization();
    const [faqs, setFaqs] = useState<FaqItemType[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        const fetchFaqs = async () => {
            setLoading(true);
            setError(null);
            try {
                // Using a cache key to refetch when language changes
                const cacheKey = `faqs_${language}`;
                const cachedFaqs = sessionStorage.getItem(cacheKey);

                if (cachedFaqs) {
                    setFaqs(JSON.parse(cachedFaqs));
                } else {
                    const generatedFaqs = await generateFaqContent(language);
                    setFaqs(generatedFaqs);
                    sessionStorage.setItem(cacheKey, JSON.stringify(generatedFaqs));
                }
            } catch (err) {
                console.error("Failed to fetch FAQs:", err);
                setError(t('faq_error_message'));
            } finally {
                setLoading(false);
            }
        };

        fetchFaqs();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [language, t]);

    return (
        <>
            <SeoHead
                title={t('faq_title')}
                description={t('faq_description')}
            />
            <div className="py-12 bg-white dark:bg-gray-800">
                <div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-4xl">
                    <div className="text-center mb-12">
                        <h1 className="text-4xl font-extrabold text-dark dark:text-white">{t('faq_h1')}</h1>
                        <p className="mt-2 text-lg text-gray-500 dark:text-gray-400">{t('faq_subtitle')}</p>
                    </div>
                    
                    {loading && (
                        <div className="flex justify-center items-center py-10">
                            <LoadingIcon />
                            <span className="ml-4 text-lg">{t('faq_loading')}</span>
                        </div>
                    )}
                    
                    {error && !loading && (
                        <div className="text-center py-10 px-4 bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300 rounded-lg">
                            <p className="text-lg font-semibold">{t('error_title')}</p>
                            <p>{error}</p>
                        </div>
                    )}

                    {!loading && !error && faqs.length > 0 && (
                        <div className="space-y-4">
                            {faqs.map((faq, index) => (
                                <FaqItem key={index} question={faq.question} answer={faq.answer} />
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </>
    );
};

export default FaqPage;
